package cn.wolfcode.shop.cloud.filter;

import com.alibaba.fastjson.JSON;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class ErrorResponseJSONFilter extends ZuulFilter {

    @Value("${error.path:/error}")
    private String errorPath;

    public ErrorResponseJSONFilter() {
    }

    public String filterType() {
        return "error";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getThrowable() != null && !ctx.getBoolean("sendErrorFilter.ran", false);
    }

    @Override

    public Object run() throws ZuulException {
        Map<String, Object> data = new HashMap<>();
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        //设置响应数据类型为json
        response.setContentType("text/json;charset=utf-8");
        if ("true".equals(currentContext.get("rateLimitExceeded"))) {
            data.put("code", 429);
            data.put("msg", "操作过于频繁,请稍后再试");
        } else {
            data.put("code", 500);
            data.put("msg", "系统繁忙");
        }
        //把数据响应回去
        try {
            response.getWriter().write(JSON.toJSONString(data));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //不走后续的filter
        currentContext.setSendZuulResponse(false);
        return null;
    }
}